package com.letu.android.widget;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

import org.json.JSONException;  
import org.json.JSONObject;
import org.json.JSONArray;

import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.ConnectivityManager;
import android.content.Context;
import android.util.Log;

public class HttpUtil {

    private static final String LOG_TAG = HttpUtil.class.getSimpleName();
    private static final int URL_CONNECTION_TIMEOUT = 20000;
    private static final int TEST_URL_CONNECTION_TIMEOUT = 1000;

    static boolean getNetworkStatus(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].getState() == NetworkInfo.State.CONNECTED) {
					return true;
					}
				}
			}
		}
		return false;
    }
    
	static String getResponseString(String requestUrl) {
		try {
			// Standard code to make an HTTP connection.
            URL url = new URL(requestUrl);
            URLConnection c = url.openConnection();
            if (!(c instanceof HttpURLConnection)) {
                Log.d(LOG_TAG, "not Http");
                return null;
            }
            
            HttpURLConnection connection = (HttpURLConnection) c;
            connection.setConnectTimeout(URL_CONNECTION_TIMEOUT);
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return null;
            }
            InputStream in = connection.getInputStream();
			StringBuffer buffer = new StringBuffer();

            try {
            	BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = bufferReader.readLine()) != null) {
                	buffer.append(line);
               	}
            } catch (IOException e) {
				Log.d(LOG_TAG, "Http util 1 exception.");
				return null;
            }
			return buffer.toString();
		} catch (Exception e) {
			Log.d(LOG_TAG, "Http util 2 exception.");
			return null;
		}
	}

	// need to close stream in outside
	static JSONObject getRequestStream(String requestUrl) {
		return getJSONObject(getResponseString(requestUrl));
	}

	static JSONArray getRequestStreamArray(String requestUrl) {
		return getJSONArray(getResponseString(requestUrl));
	}

	static JSONArray getJSONArray(String str) {
		if (str == null || str.trim().length() == 0)  
			return null;  
		JSONArray array = null;  
		try {
			array = new JSONArray(str);  
		} catch (JSONException e) {  
			e.printStackTrace(System.err);  
		}
		return array;  
	}

	static JSONObject getJSONObject(String str) {  
		if (str == null || str.trim().length() == 0)  
			return null;  
		JSONObject jsonObject = null;  
		try {  
			jsonObject = new JSONObject(str);  
		} catch (JSONException e) {  
			e.printStackTrace(System.err);  
		}
		return jsonObject;  
	}
	
	static final String STATUS = "status";
	static final String COUNT = "count";
	static final String MSG = "msg";
	static final String ID = "id";
	static final String TITLE = "title";
	static final String IMAGE = "img";
	static final String CONTENT = "content";
	static final String RATING = "rating";
	static final String TYPE = "type";
	static final String FLAG = "flag";
	static final String OPENTIME = "opentime";
	static final String TICKET = "ticket";
	static final String ADDRESS = "address";
	static final String PROJECT = "projectname";
	static final String PRICE = "price";
	static final String PHONE = "phone";
	static final String USERNAME = "username";
	
	private static String formatUrl(String dest, Context context) {
		String colon = context.getString(R.string.colon);
		String forward_slash = context.getString(R.string.forward_slash);
		return dest.replaceAll(forward_slash, "/").replaceAll(colon, ":");
	}

	static String[][] parseSearchResult(JSONObject object) {
		Log.d("parseSearchResult 1", ""+(object==null));
		if (object == null)
			return null;
		int status = object.optInt(STATUS);
		Log.d("parseSearchResult 2", ""+status);
		if (status == 0) {
			return null;
		}
		int count = object.optInt(COUNT);
		JSONArray array = object.optJSONArray(MSG);
		String result[][] = new String[2][array.length()];
		for (int i = 0; i < array.length(); i++) {
			JSONObject item = array.optJSONObject(i);
			result[0][i] = item.optString(ID);
			result[1][i] = item.optString(TITLE);
		}
		return result;
	}

	static String[][] parseMonthRecommend(JSONArray array) {
		if (array == null)
			return null;
		int count = array.length();
		String result[][] = new String[2][count];
		for (int i = 0; i < count; i++) {
			JSONObject item = array.optJSONObject(i);
			result[0][i] = item.optString(ID);
			result[1][i] = item.optString(TITLE);
		}
		return result;
	}

	static int parseSearchResultCount(JSONObject object) {
		if (object == null)
			return 0;
		int status = object.optInt(STATUS);
		if (status == 0) {
			return 0;
		}
		int count = object.optInt(COUNT);
		return (count < 0 ? 0 : count);
	}

	static HashMap<String, String> parseScentSpot(JSONObject object, Context context) {
		if (object == null)
			return null;
		int status = object.optInt(STATUS);
		if (status == 0)
			return null;

		HashMap <String, String> map = new HashMap<String, String>();

		String title = object.optString(TITLE);
		String content = object.optString(CONTENT);
		String image = object.optString(IMAGE);

		map.put(TITLE, title);
		map.put(CONTENT, content);
		map.put(IMAGE, replaceSBC(image, context));
		return map;
	}

	public static String replaceSBC(String dest, Context context) {
		String forward_slash = context.getResources().getString(R.string.forward_slash) ;
		String colon = context.getResources().getString(R.string.colon) ;
		dest = dest.replaceAll(colon, ":");
		dest = dest.replaceAll(forward_slash, "/");
		return dest;
 	}

	/*static HashMap<String, String> parseSceneArea(JSONObject object, Context context) {
		if (object == null)
			return null;
		int status = object.optInt(STATUS);
		if (status == 0)
			return null;

		HashMap <String, String> map = new HashMap<String, String>();

		String title = object.optString(TITLE);
		String content = object.optString(CONTENT);
		String rating = object.optString(RATING);
		String type = object.optString(TYPE);
		String opentime = object.optString(OPENTIME);
		String ticket = object.optString(TICKET);
		String address = object.optString(ADDRESS);
		String phone = object.optString(PHONE);
		String image = object.optString(IMAGE);

		map.put(TITLE, title);
		map.put(CONTENT, content);
		map.put(RATING, rating);
		map.put(TYPE, type);
		map.put(OPENTIME, opentime);
		map.put(TICKET, ticket);
		map.put(ADDRESS, address);
		map.put(PHONE, phone);
		map.put(IMAGE, replaceSBC(image, context));

		return map;
	}*/

	static String[] parseSceneArea(JSONObject object, Context context) {
		if (object == null)
			return null;
		int status = object.optInt(STATUS);
		if (status == 0)
			return null;

		String result[] = new String[9];

		String title = object.optString(TITLE);
		String content = object.optString(CONTENT);
		String rating = object.optString(RATING);
		String type = object.optString(TYPE);
		String opentime = object.optString(OPENTIME);
		String ticket = object.optString(TICKET);
		String address = object.optString(ADDRESS);
		String phone = object.optString(PHONE);
		String image = object.optString(IMAGE);

		result[0] = title;
		result[1] = content;
		result[2] = rating;
		result[3] = type;
		result[4] = opentime;
		result[5] = ticket;
		result[6] = address;
		result[7] = phone;
		result[8] = replaceSBC(image, context);

		return result;
	}
	
	static String[][] parseRecommendScene(JSONObject object) {
		if (object == null)
			return null;
		int status = object.optInt(STATUS);
		if (status == 0)
			return null;

		JSONArray array = object.optJSONArray(MSG);
		int count = array.length();
		String result[][] = new String[2][count];

		for (int i = 0; i < count; i++) {
			JSONObject item = array.optJSONObject(i);
			result[0][i] = item.optString(ID);
			result[1][i] = item.optString(TITLE);
		}

		return result;
	}

	static String[][] parseAroundScene(JSONObject object) {
		return parseRecommendScene(object);
	}

	static String[] parseRoute(JSONObject object) {
		if (object == null)
			return null;
		int status = object.optInt(STATUS);
		if (status == 0)
			return null;

		JSONArray array = object.optJSONArray(MSG);
		int count = array.length();
		String result[] = new String[count * 6];
		for (int i = 0; i < count; i++) {
			JSONObject item = array.optJSONObject(i);
			result[i * 6] = item.optString(ID);
			result[i * 6 + 1] = item.optString(TITLE);
			result[i * 6 + 2] = item.optString(PROJECT);
			result[i * 6 + 3] = item.optString(PRICE);
			result[i * 6 + 4] = item.optString(PHONE);
			result[i * 6 + 5] = item.optString(TYPE);
		}
		return result;
	}

	static String[] parseNoteList(JSONObject object) {
		if (object == null)
			return null;
		int status = object.optInt(STATUS);
		if (status == 0)
			return null;

		JSONArray array = object.optJSONArray(MSG);
		int count = array.length();
		String result[] = new String[count * 3];
		for (int i = 0; i < count; i++) {
			JSONObject item = array.optJSONObject(i);
			result[i * 3] = item.optString(ID);
			result[i * 3 + 1] = item.optString(TITLE);
			result[i * 3 + 2] = item.optString(FLAG);
		}
		return result;
	}

	static HashMap <String, String> parseNoteContent(JSONObject object, Context context) {
		if (object == null)
			return null;
		int status = object.optInt(STATUS);
		if (status == 0)
			return null;

		HashMap <String, String> map = new HashMap<String, String>();

		String id = object.optString(ID);
		String title = object.optString(TITLE);
		String content = object.optString(CONTENT);
		String username = object.optString(USERNAME);
		//String image = object.optString(IMAGE);		
		//String type = object.optString(TYPE);
		
		map.put(ID, id);
		map.put(TITLE, title);
		map.put(CONTENT, content);
		map.put(USERNAME, username);
		//map.put(IMAGE, replaceSBC(image, context));		
		//map.put(TYPE, type);
		return map;
	}

	static String[][] parseHotLineList(JSONObject object) {
		return parseRecommendScene(object);
	}

	static HashMap<String, String> parseHotLineContent(JSONObject object, Context context) {
		if (object == null)
			return null;
		int status = object.optInt(STATUS);
		if (status == 0)
			return null;

		HashMap <String, String> map = new HashMap<String, String>();

		String id= object.optString(ID);
		String title = object.optString(TITLE);

		map.put(ID, id);
		map.put(TITLE, title);

		return map;
	}
}
